package com.qb.devinfo;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.Window;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;

import Adapter.ItemAdapter;
import Adapter.TypeAdapter;
import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import utils.DevInfoUtil;
import utils.LoadingUtil;
import utils.MyUtil;
import utils.SystemPropertiesReflection;

public class MainActivity extends AppCompatActivity {

    public static MainActivity mActivity;
    public String loginBtn = "点击获取基本信息";
    Context ctx;
    JSONArray typeData,itemData;
    SharedPreferences SP;
    Dialog loading;
    private RecyclerView rvType,rvItem;
    private Boolean isTypeClick = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ctx = MainActivity.this;
        mActivity = this;
        Window window = this.getWindow();
        window.setStatusBarColor(getResources().getColor(R.color.primary_normal));

        SP = getSharedPreferences("dev_mgt_setting", this.MODE_PRIVATE);
        SharedPreferences.Editor edit = SP.edit();
        edit.putString("baseUrl","https://www.androidgmt.com/manager");
//        edit.putString("baseUrl","http://192.168.6.95:65533");
        edit.apply();

        rvType = findViewById(R.id.rv_type);
        rvItem = findViewById(R.id.rv_item);
        dataInit(false);
        new Handler().postDelayed(()-> {
            login();
        },1);

        /*
        String t = DevInfoUtil.getBootTime();
        String a = SystemPropertiesReflection.demo;
        MyUtil.showLog("aaaaaaaaaaaaaa",a);

        MyUtil.showLog("bbbbbbbbbb",MyUtil.transferLongToDate("yyyy-MM-dd HH:mm:ss",SystemPropertiesReflection.getLong("ro.build.date.utc") * 1000));
        long b = System.currentTimeMillis();
        MyUtil.showLog("bbbbbbbbbb",MyUtil.transferLongToDate("yyyy-MM-dd HH:mm:ss",b));

         */
    }

    public void login() {
        loading = LoadingUtil.create(ctx, "数据加载中");
        String post_sn = DevInfoUtil.getSN()+"@|@"+"EquipmentInfo";
        // post formbody
        httpAction("login","/AndroidGmtService/Token/TakeToken?board_sn_process="+post_sn,"post","");

        // post application/json
        /*JSONObject p = new JSONObject();
        try {
            p.put("board_sn_process",post_sn);
            httpAction("login","/AndroidGmtService/Token/TakeToken","post",p.toString());
        } catch (JSONException e) {
            e.printStackTrace();
            Toast.makeText(ctx, "获取数据失败", Toast.LENGTH_SHORT).show();
        }*/
    }

    private void initAdapter(Boolean loadData) {
        LinearLayoutManager typeLLM = new LinearLayoutManager(this);
        typeLLM.setOrientation(LinearLayoutManager.VERTICAL);
        rvType.setLayoutManager(typeLLM);
        TypeAdapter typeAdapter = new TypeAdapter(this, typeData);
        rvType.setAdapter(typeAdapter);

        LinearLayoutManager itemLLM = new LinearLayoutManager(this);
        itemLLM.setOrientation(LinearLayoutManager.VERTICAL);
        rvItem.setLayoutManager(itemLLM);
        ItemAdapter itemAdapter = new ItemAdapter(this, itemData);
        rvItem.setAdapter(itemAdapter);

        // 左联右
        typeAdapter.setOnItemClickListener(new TypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                try {
                    isTypeClick = true;
                    int first = itemLLM.findFirstCompletelyVisibleItemPosition();
                    int last = itemLLM.findLastCompletelyVisibleItemPosition();
//                MyUtil.showLog("first:"+first,"last:"+last+",click:"+itemData.length());
                    int top = 0;
                    int tpn = 0;
                    if (position == 0) {
                        top = 0;
                        rvItem.smoothScrollToPosition(0);
                    } else if (position == 1) {
                        tpn = loadData?4:2;
                        if (first > tpn) {
                            rvItem.smoothScrollToPosition(tpn);
                        } else {
                            top  = rvItem.getChildAt(tpn).getTop();
                        }
                    } else if (position == 2) {
                        if (first > 10) {
                            tpn = loadData?11:9;
                            rvItem.smoothScrollToPosition(tpn);
                        } else if ( last < 12 ) {
                            tpn = loadData?20:18;
                            rvItem.smoothScrollToPosition(tpn);
                        } else {
                            top  = rvItem.getChildAt(last - 6).getTop();
                        }
                    } else if (position == 3) {
                        tpn = loadData?22:20;
                        if (last < tpn) {
                            rvItem.smoothScrollToPosition(tpn);
                        } else {
                            top  = rvItem.getChildAt(last - tpn).getTop();
                        }
                    } else {
                        top = 0;
                        rvItem.smoothScrollToPosition(itemData.length()-1);
                    }
                    if (top > 0) rvItem.smoothScrollBy(0, top);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        // 右联左
        rvItem.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE){
                    try {
//                    MyUtil.showLog("isTypeClick",isTypeClick);
                        if (isTypeClick) {
                            isTypeClick = false;
                        } else {
                            int first = itemLLM.findFirstCompletelyVisibleItemPosition();
                            int last = itemLLM.findLastCompletelyVisibleItemPosition();
//                        MyUtil.showLog("first:"+first,"last:"+last+",scroll:"+itemData.length());
                            if (first <= 1) typeAdapter.selectedEffect(0);
                            else if (last == itemData.length()-1) typeAdapter.selectedEffect(typeData.length() - 1);
                            else if (first >= (loadData?4:2) &&  first < (loadData?9:7)) typeAdapter.selectedEffect(1);
                            else if (first >= (loadData?9:7) &&  first <= (loadData?10:11)) typeAdapter.selectedEffect(2);
                            else if (first > (loadData?10:11) &&  first <= 16) typeAdapter.selectedEffect(3);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    public void dataInit(Boolean loadData) {
        String[] type = {"基本信息","关于终端","屏幕","网络","蓝牙"};
        JSONObject o;
        try {
            // type
            typeData = new JSONArray();
            for (int i=0;i<type.length;i++) {
                //if (!loadData && i == 0) continue;
                o = new JSONObject();
                int icon = R.drawable.icon_baseline_info_32;
                if (type[i].equals("基本信息")) icon = R.drawable.icon_baseline_info_32;
                if (type[i].equals("关于终端")) icon = R.drawable.icon_baseline_devices_32;
                if (type[i].equals("屏幕")) icon = R.drawable.icon_baseline_desktop_mac_32;
                if (type[i].equals("网络")) icon = R.drawable.icon_baseline_wifi_32;
                if (type[i].equals("蓝牙")) icon = R.drawable.icon_baseline_bluetooth_32;
                o.put("icon",icon);
                o.put("label",type[i]);
                typeData.put(o);
            }
            // item
            itemData = new JSONArray();
            if (loadData) {
                o = new JSONObject();
                o.put("key","title");
                o.put("value",type[0]);
                itemData.put(o);
                o = new JSONObject();
                o.put("key","所属用户");
                String clientName = SP.getString("clientName","");
                o.put("value",MyUtil.isNull(clientName)?"未知":clientName);
                itemData.put(o);
                o = new JSONObject();
                o.put("key","设备型号");
                String model = SP.getString("model","");
                o.put("value",MyUtil.isNull(model)?"未知":model);
                itemData.put(o);
                o = new JSONObject();
                o.put("key","设备序列号");
                String sn = SP.getString("sn","");
                o.put("value",sn);
                itemData.put(o);
            } else {
                o = new JSONObject();
                o.put("key","title");
                o.put("value",type[0]);
                itemData.put(o);
                o = new JSONObject();
                o.put("key","基本信息");
                o.put("value",loginBtn);
                itemData.put(o);
            }
            o = new JSONObject();
            o.put("key","title");
            o.put("value",type[1]);
            itemData.put(o);
            o = new JSONObject();
            o.put("key","主板序列号");
            o.put("value", DevInfoUtil.getSN());
            itemData.put(o);
            o = new JSONObject();
            o.put("key","处理器");
            String cpu = DevInfoUtil.getCpuInfo("Hardware");
            o.put("value",cpu.split("EVB")[0]);
            itemData.put(o);
            o = new JSONObject();
            o.put("key","运行内存(可用/总)");
            String ram = DevInfoUtil.getRAM(ctx).getString("avail")+"/"+DevInfoUtil.getRAM(ctx).getString("total");
            o.put("value",ram);
            itemData.put(o);
            o = new JSONObject();
            o.put("key","存储(可用/总)");
            String rom = DevInfoUtil.getROM(ctx).getString("avail")+"/"+DevInfoUtil.getROM(ctx).getString("total");
            o.put("value",rom);
            itemData.put(o);
            o = new JSONObject();
            o.put("key","Android版本");
            o.put("value",DevInfoUtil.getOsInfo());
            itemData.put(o);
            o = new JSONObject();
            o.put("key","系统版本号");
            o.put("value",SystemPropertiesReflection.get("ro.build.display.id"));
            itemData.put(o);
            o = new JSONObject();
            o.put("key","title");
            o.put("value",type[2]);
            itemData.put(o);
            JSONArray screenInfo = DevInfoUtil.getScreenInfo(ctx);
            for(int i=0;i<screenInfo.length();i++) {
                o = new JSONObject();
                if (i==0) o.put("key","主屏");
                else if (i==1)  o.put("key","副屏");
                else o.put("key","副屏"+i);
                o.put("value","分辨率"+screenInfo.get(i).toString());
                itemData.put(o);
            }
            o = new JSONObject();
            o.put("key","title");
            o.put("value",type[3]);
            itemData.put(o);
            JSONArray netType = DevInfoUtil.getNetworkType(ctx);
            for(int i=0;i<netType.length();i++) {
                JSONObject netTYpe_o = new JSONObject(netType.get(i).toString());
                if (!MyUtil.isNull(netTYpe_o)) {
                    o = new JSONObject();
                    o.put("key","网络类型");
                    o.put("value",netTYpe_o.getString("type"));
                    itemData.put(o);
                    o = new JSONObject();
                    o.put("key","MAC地址");
                    String mac_address = SP.getString("mac_address","");
                    String mac = "unknown";
                    try {
                        mac = netTYpe_o.getString("mac");
                    } catch(Exception e) {}
                    o.put("value",MyUtil.isNull(mac_address)?mac:mac_address);
                    itemData.put(o);
                }
            }
            JSONArray localIp = DevInfoUtil.getLocalIP();
            for(int i=0;i<localIp.length();i++) {
                JSONObject localIp_o = new JSONObject(localIp.get(i).toString());
                if (!MyUtil.isNull(localIp_o)) {
                    o = new JSONObject();
                    o.put("key","局域网类型");
                    o.put("value",localIp_o.getString("type"));
                    itemData.put(o);
                    o = new JSONObject();
                    o.put("key","ipv6地址");
                    o.put("value",localIp_o.getString("ipv6"));
                    itemData.put(o);
                    o = new JSONObject();
                    o.put("key","ipv4地址");
                    o.put("value",localIp_o.getString("ipv4"));
                    itemData.put(o);
                }
            }
            o = new JSONObject();
            o.put("key","title");
            o.put("value",type[4]);
            itemData.put(o);
            JSONObject bleInfo = DevInfoUtil.getBleInfo(ctx);
            o = new JSONObject();
            o.put("key","蓝牙名称");
            o.put("value",bleInfo.getString("name"));
            itemData.put(o);
            o = new JSONObject();
            o.put("key","蓝牙MAC地址");
            String bt_mac_address = SP.getString("bt_mac_address","");
            String btmac = "unknown";
            try {
                btmac = bleInfo.getString("mac");
            } catch(Exception e) {}
            o.put("value",MyUtil.isNull(bt_mac_address)?btmac:bt_mac_address);
            itemData.put(o);
//            o = new JSONObject();
//            o.put("key","蓝牙版本");
//            o.put("value",bleInfo.getString("version"));
//            itemData.put(o);
            initAdapter(loadData);
        } catch (JSONException e) {
            e.printStackTrace();
            Toast.makeText(ctx, "设备信息获取失败 "+e.getMessage(), Toast.LENGTH_SHORT);
        }
    }
    /*
     * http
     * */
    public void httpAction(String flag,String url,String method,String postJson) {
        String BaseUrl = SP.getString("baseUrl","");
        if (BaseUrl.indexOf(".") < 10) {
            Toast.makeText(ctx, "无效的服务器"+BaseUrl, Toast.LENGTH_SHORT).show();
            return;
        }
        url = BaseUrl+url;
        String token = SP.getString("token","");

        MyUtil.showLog("********url********", url);
        MyUtil.showLog("********token********", token);
        MyUtil.showLog("********postJson********", postJson);

        OkHttpClient ohc = new OkHttpClient();
        Request request = null;
        if (method.equals("get")) {
            request = new Request.Builder().url(url)
                    .addHeader("Authorization", "Bearer "+token)
                    .build();
        }
        if (method.equals("post")) {
            RequestBody requestBody;
            if (flag.equals("login")) {
                // formBody
                HashMap<String,String> paramsMap = new HashMap<>();
                paramsMap.put("board_sn_process",postJson);
                FormBody.Builder builder = new FormBody.Builder();
                for (String key : paramsMap.keySet()) {
                    builder.add(key, paramsMap.get(key));
                }
                requestBody = builder.build();
            } else {
                // json
                requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), postJson);
            }
            request = new Request.Builder().url(url).post(requestBody)
                    .addHeader("Authorization", "Bearer "+token)
                    .build();
        }
        ohc.newCall(request).enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                MyUtil.showLog("httpAction onFailure",e.getMessage());
                runOnUiThread(() -> {
                    LoadingUtil.close(loading);
                    Toast.makeText(ctx, "网络连接失败 "+e.getMessage(), Toast.LENGTH_SHORT).show();
                });
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                MyUtil.showLog("httpAction onResponse", response);
                successResult(response, flag);
            }
        });
    }
    public void successResult(Response res, String flag) {
        if (res.code() == 200) {
            try {
                String r = "{}";
                try {
                    r = res.body().string();
                    MyUtil.showLog("httpAction success",r);
                } catch (Exception e) {
                    Toast.makeText(ctx, "HTTP返回数据获取失败 "+e.getMessage(), Toast.LENGTH_SHORT).show();
                    e.printStackTrace();
                }
                JSONObject rObj = new JSONObject(r);
                String rCode = rObj.get("returnCode").toString();
                String rMsg = rObj.get("message").toString();
                if (rCode.equals("10000")) {
                    String dStr = rObj.get("data").toString();
                    JSONArray data = new JSONArray(MyUtil.isNull(dStr)?"[]":dStr);
                    runOnUiThread(() -> {
                        LoadingUtil.close(loading);
                        try {
                            if (!MyUtil.isNull(data.get(0).toString())) {
                                SharedPreferences.Editor edit = SP.edit();
                                JSONObject d0 = new JSONObject(data.get(0).toString());
                                MyUtil.showLog("********d0********", String.valueOf(d0));
                                if (flag.equals("login")) {
                                    String token = d0.getString("token");
                                    edit.putString("token",token);
                                    edit.apply();
                                    JSONObject p = new JSONObject();
                                    p.put("id",DevInfoUtil.getSN()+"@|@"+"DeviceInfo");
                                    p.put("token",token);
                                    httpAction("qryDevice","/AndroidGmtService/Devices/QryDevice","post",p.toString());
                                };
                                if (flag.equals("qryDevice")) {
                                    edit.putString("sn",d0.getString("sn"));
                                    String plat_user = d0.getJSONObject("plat_user").getString("name");
                                    edit.putString("clientName",plat_user);
                                    String equipment_model = d0.getJSONObject("equipment_model").getString("model");
                                    edit.putString("model",equipment_model);
                                    JSONArray setups = d0.getJSONArray("setups");
                                    for(int i=0;i<setups.length();i++) {
                                        JSONObject s = new JSONObject(setups.get(i).toString());
                                        if (s.getString("key").equals("MAC地址")) {
                                            edit.putString("mac_address",s.getString("value"));
                                        }
                                        if (s.getString("key").equals("蓝牙MAC地址")) {
                                            edit.putString("bt_mac_address",s.getString("value"));
                                        }
                                    }
                                    edit.apply();
                                    dataInit(true);
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    });
                } else {
                    LoadingUtil.close(loading);
                    if (rMsg.indexOf("设备不存在")>=0) rMsg="此设备没有登记到终端管理平台";
                    String finalRMsg = rMsg;
                    runOnUiThread(() -> {
                        Toast.makeText(ctx, finalRMsg, Toast.LENGTH_SHORT).show();
                    });
                }
            } catch (JSONException e) {
                runOnUiThread(() -> {
                    LoadingUtil.close(loading);
                    Toast.makeText(ctx, "查询失败 "+e.getMessage(), Toast.LENGTH_SHORT).show();
                });
                e.printStackTrace();
            }
        } else {
            runOnUiThread(() -> {
                LoadingUtil.close(loading);
                Toast.makeText(ctx, "查询失败 "+res.code(), Toast.LENGTH_SHORT).show();
            });
        }
    }
}